use crate::error::ErrorBacktrace;
use std::collections::HashSet;

#[derive(thiserror::Error, Debug)]
#[error("{source}\n{backtrace}")]
pub struct ValidationErrors {
    pub source: validator::ValidationErrors,
    pub backtrace: ErrorBacktrace,
}

impl From<validator::ValidationErrors> for ValidationErrors {
    fn from(source: validator::ValidationErrors) -> Self {
        Self {
            source,
            backtrace: Default::default(),
        }
    }
}

pub fn validate_string_is_not_empty(v: &str) -> Result<(), validator::ValidationError> {
    if v.is_empty() {
        return Err(
            validator::ValidationError::new("string_is_not_empty").with_message("不能为空".into())
        );
    }
    Ok(())
}

pub fn validate_not_allowed_duplicate<T>(v: &[T]) -> Result<(), validator::ValidationError>
where
    T: Eq + std::hash::Hash,
{
    let mut seen = HashSet::new();
    for item in v {
        if !seen.insert(item) {
            return Err(validator::ValidationError::new("not_allowed_duplicate")
                .with_message("不能有重复元素".into()));
        }
    }
    Ok(())
}
